<?php

define('GAAPI_LIB_PATH', dirname(__FILE__). '/');
define('GAAPI_CLIENTS_PATH', GAAPI_LIB_PATH . 'Clients/');
define('GAAPI_DEPENDENCIES_PATH', GAAPI_LIB_PATH . 'dependencies/');
define('GAAPI_METHODS_PATH', GAAPI_LIB_PATH . 'services/');
define('GAAPI_OBJECTS_PATH', GAAPI_LIB_PATH . 'objects/');

require GAAPI_LIB_PATH . 'Autoloader.php';

class GaAPI {
    public $email;
    public $password;
    public $client_id;
    public $client_email;
    public $developer_token;
    public $application_token;

    public $use_sandbox = true;
    protected $_services = array();

    public function  __call($name, $arguments) {
        try {
            if (!isset ($this->_services[$name])) {
                GaAPI_Autoloader::instance()->load('GaAPI_Services_Abstract');
                $className = 'GaAPI_Services_' . $name;
                GaAPI_Autoloader::instance()->load($className);
                $this->_services[$name] = new $className();
                $this->_services[$name]->setApi($this);
            }

            return $this->_services[$name];
        } catch (Exception $e) {
            echo 'GaAPI exception: ',  $e->getMessage(), "\n";
        }
    }

    public function useSandbox($value) {
        $this->use_sandbox = ($value === false) ? false : true;
    }

    public function isSandbox() {
        return $this->use_sandbox == true;
    }


    public function getAuthToken() {
        if (!$this->_authToken) {
            GaAPI_Autoloader::instance()->load('GaAPI_Auth');
            $auth = new GaAPI_Auth($this->email, $this->password, 'GOOGLE', 'adwords');
            $this->_authToken = $auth->get_auth_token();
        }

        return $this->_authToken;
    }

    public function login($email, $password, $developer_token, $application_token) {
        $this->email = $email;
        $this->password = $password;
        $this->developer_token = $developer_token;
        $this->application_token = $application_token;
    }

    public function checkLoginParams() {
        $params = $this->getLoginParams();
        foreach ($params as $param) {
            $this->checkParam($param);
        }
    }


    public function checkParam($param) {
        if (empty ($this->$param)) {
            $this->throwError("Required parameter [{$param}] not set");
            return false;
        }
        return true;
    }


    protected function getLoginParams() {
        return array('email', 'password', 'developer_token', 'application_token');
    }

    public function throwError($error_msg) {
        throw new Exception($error_msg);
    }


    public function resetCall() {
        $this->client_id = '';
        $this->client_email = '';
    }
}